package com.tj.collection.task;

import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.tj.collection.db.dao.CusomExtDao;
import com.tj.collection.db.dao.RptChatsPaymentDataPreDayDao;
import com.tj.collection.db.dao.RptCustomQuerySqlDao;
import com.tj.collection.db.entity.RptChatsPaymentDataPreDayEntity;
import com.tj.collection.db.entity.RptCustomQuerySqlEntity;
import com.tj.collection.enums.DataReportTypeEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * chatter 每日数据统计
 */
@Service
public class ChatsPaymentDataTask {

    private static Log logger = LogFactory.getLog(ChatsPaymentDataTask.class);
    @Resource
    RptCustomQuerySqlDao customQuerySqlDao;
    @Resource
    RptChatsPaymentDataPreDayDao chatsPaymentDataPreDayDao;
    @Resource
    CusomExtDao cusomExtDao;

    /**
     * 当前在线用户数统计
     */
    @Scheduled(fixedDelay = 1000 * 600)
    public void chatsPaymentDataTask() {

        // 删除当前时段数据
        final RptChatsPaymentDataPreDayEntity chatsPaymentData = chatsPaymentDataPreDayDao.getPreData();
        if (chatsPaymentData == null) {
            RptChatsPaymentDataPreDayEntity newRecord = new RptChatsPaymentDataPreDayEntity();
            newRecord.setCreateDt(Integer.valueOf(cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMMdd")));
            chatsPaymentDataPreDayDao.insert(newRecord);
        }


        // 重新统计当前时段在线数据
        final List<RptCustomQuerySqlEntity> customSqlList = getCustomSqlList(DataReportTypeEnum.CHATS_PAYMENT_DATA.getType());
        if (CollectionUtils.isEmpty(customSqlList)) {
            return;
        }
        for (RptCustomQuerySqlEntity customQuerySql : customSqlList) {
            logger.info("====name{}， sql:{}", customQuerySql.getName(), customQuerySql.getSqlText());
            final List<Map<String, Object>> records = cusomExtDao.customQuery2(customQuerySql.getSqlText());
            if (CollectionUtils.isEmpty(records)) {
                continue;
            }
            for (Map<String, Object> item : records) {

                final String updateSql = cusomExtDao.buildUpdateSql(customQuerySql, item);
                if (StringUtils.isEmpty(updateSql)) {
                    continue;
                }
                cusomExtDao.updateCustomerSql(updateSql);
                // 只执行一次
                if (customQuerySql.getExecuteOnceFlag() == 1) {
                    break;
                }
            }

        }


    }

    private List<RptCustomQuerySqlEntity> getCustomSqlList(Integer type) {
        return customQuerySqlDao.listRptCustomQuerySqlByType(type);
    }


}
